package com.ultimatech.wxservice.web.filter;

import com.ultimatech.webappdemo.authmgr.dao.IAuthDao;
import com.ultimatech.webappdemo.authmgr.service.IAuthService;
import com.ultimatech.webappdemo.base.model.SysUser;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Created by 张乐平 on 8/3 0003.
 */
public class RememberAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private IAuthDao authDao;

    public IAuthDao getAuthDao() {
        return authDao;
    }

    public void setAuthDao(IAuthDao authDao) {
        this.authDao = authDao;
    }

    @Autowired
    private IAuthService authService;

    public IAuthService getAuthService() {
        return authService;
    }

    public void setAuthService(IAuthService authService) {
        this.authService = authService;
    }

    /**
     * 这个方法决定了是否能让用户登录
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);

        //如果 isAuthenticated 为 false 证明不是登录过的，同时 isRememberd 为true 证明是没登陆直接通过记住我功能进来的
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            //如果是空的才初始化，否则每次都要初始化，项目得慢死
            //这边根据前面的前提假设，拿到的是username
            String username = subject.getPrincipal().toString();
            //在这个方法里面做初始化用户上下文的事情，比如通过查询数据库来设置session值，你们自己发挥
            SysUser user = this.getAuthDao().findByName(username);
            if (user != null) {
                this.getAuthService().logIn(user.getUsername(), user.getPassword(), true);
            }
        }

        //这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered() 让它同时也兼容remember这种情况
        return subject.isAuthenticated() || subject.isRemembered();
    }
}
